<template>
  <div class="work-order-reports page-container">
    <div class="page-header">
      <h2>工单报表</h2>
      <div>
        <el-button type="primary" @click="refreshData" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
        <el-button type="success" @click="exportReport">
          <el-icon><Download /></el-icon>
          导出报表
        </el-button>
      </div>
    </div>

    <!-- 时间筛选 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="统计时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="统计维度">
          <el-select v-model="filterForm.dimension" style="width: 120px">
            <el-option label="按天" value="day" />
            <el-option label="按周" value="week" />
            <el-option label="按月" value="month" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadReportData">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计概览 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-value">{{ stats.total }}</div>
            <div class="stats-label">总工单数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-value">{{ stats.completed }}</div>
            <div class="stats-label">已完成</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-value">{{ stats.pending }}</div>
            <div class="stats-label">待处理</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-value">{{ stats.completionRate }}%</div>
            <div class="stats-label">完成率</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card title="工单状态分布">
          <template #header>
            <span>工单状态分布</span>
          </template>
          <div ref="statusChartRef" style="height: 300px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card title="工单优先级分布">
          <template #header>
            <span>工单优先级分布</span>
          </template>
          <div ref="priorityChartRef" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card title="工单趋势图">
          <template #header>
            <span>工单创建趋势</span>
          </template>
          <div ref="trendChartRef" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细数据表格 -->
    <el-card style="margin-top: 20px;">
      <template #header>
        <span>详细统计数据</span>
      </template>
      <el-table :data="detailData" v-loading="loading" stripe>
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="total" label="总数" width="80" />
        <el-table-column prop="pending" label="待处理" width="80" />
        <el-table-column prop="processing" label="处理中" width="80" />
        <el-table-column prop="completed" label="已完成" width="80" />
        <el-table-column prop="cancelled" label="已取消" width="80" />
        <el-table-column prop="completion_rate" label="完成率" width="100">
          <template #default="{ row }">
            {{ row.completion_rate }}%
          </template>
        </el-table-column>
        <el-table-column prop="avg_duration" label="平均处理时长" width="120" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Download } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { workOrdersApi } from '@/api'

const loading = ref(false)

const filterForm = reactive({
  dateRange: [
    new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
    new Date().toISOString().split('T')[0]
  ] as [string, string],
  dimension: 'day'
})

const stats = ref({
  total: 0,
  completed: 0,
  pending: 0,
  processing: 0,
  completionRate: 0
})

const detailData = ref([])
const statusDistribution = ref({})
const priorityDistribution = ref({})
const trendData = ref([])

// 图表引用
const statusChartRef = ref<HTMLDivElement>()
const priorityChartRef = ref<HTMLDivElement>()
const trendChartRef = ref<HTMLDivElement>()

// 图表实例
let statusChart: echarts.ECharts | null = null
let priorityChart: echarts.ECharts | null = null
let trendChart: echarts.ECharts | null = null

const loadReportData = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      start_date: filterForm.dateRange[0],
      end_date: filterForm.dateRange[1],
      dimension: filterForm.dimension,
      type: 'overview'  // 获取概览报表
    }

    // 调用API获取报表数据
    const response = await workOrdersApi.getWorkOrderReports(params)
    const data = response.data
    
    // 更新统计数据 - 适配新的API结构
    if (data.overview) {
      stats.value = {
        total: data.overview.total || 0,
        completed: data.overview.completed || 0,
        pending: data.overview.pending || 0,
        processing: data.overview.processing || 0,
        completionRate: data.overview.completion_rate || 0
      }
    }
    
    // 状态和优先级分布
    statusDistribution.value = data.status_distribution || {}
    priorityDistribution.value = data.priority_distribution || {}
    
    // 获取趋势数据
    const trendParams = {
      start_date: filterForm.dateRange[0],
      end_date: filterForm.dateRange[1],
      dimension: filterForm.dimension,
      type: 'trend'
    }
    const trendResponse = await workOrdersApi.getWorkOrderReports(trendParams)
    trendData.value = trendResponse.data.trend_data || []
    
    // 设置详细数据表格
    detailData.value = trendData.value.map(item => ({
      date: item.date,
      total: item.total,
      pending: item.pending,
      processing: item.processing,
      completed: item.completed,
      cancelled: item.cancelled,
      completion_rate: item.completion_rate,
      avg_duration: '-'  // 暂时设为默认值
    }))
    
    // 重新渲染图表
    await nextTick()
    renderCharts()
    
  } catch (error) {
    console.error('加载报表数据失败:', error)
    ElMessage.error('加载报表数据失败')
  } finally {
    loading.value = false
  }
}

const refreshData = () => {
  loadReportData()
}

const exportReport = () => {
  // 导出CSV格式的报表数据
  try {
    const csvContent = generateCSV()
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `工单报表_${filterForm.dateRange[0]}_${filterForm.dateRange[1]}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    ElMessage.success('报表导出成功')
  } catch (error) {
    console.error('导出报表失败:', error)
    ElMessage.error('导出报表失败')
  }
}

const generateCSV = () => {
  const headers = ['日期', '总数', '待处理', '处理中', '已完成', '已取消', '完成率(%)', '平均处理时长']
  const rows = detailData.value.map((item: any) => [
    item.date,
    item.total,
    item.pending,
    item.processing,
    item.completed,
    item.cancelled,
    item.completion_rate,
    item.avg_duration
  ])
  
  const csvContent = [headers, ...rows]
    .map(row => row.join(','))
    .join('\n')
  
  return '\uFEFF' + csvContent // 添加BOM以支持中文
}

const renderCharts = () => {
  // 渲染状态分布饼图
  if (statusChartRef.value) {
    if (statusChart) {
      statusChart.dispose()
    }
    statusChart = echarts.init(statusChartRef.value)
    
    const statusData = Object.entries(statusDistribution.value).map(([key, value]) => ({
      name: getStatusLabel(key),
      value: value
    }))
    
    const statusOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '工单状态',
          type: 'pie',
          radius: '50%',
          data: statusData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    
    statusChart.setOption(statusOption)
  }
  
  // 渲染优先级分布饼图
  if (priorityChartRef.value) {
    if (priorityChart) {
      priorityChart.dispose()
    }
    priorityChart = echarts.init(priorityChartRef.value)
    
    const priorityData = Object.entries(priorityDistribution.value).map(([key, value]) => ({
      name: getPriorityLabel(key),
      value: value
    }))
    
    const priorityOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '工单优先级',
          type: 'pie',
          radius: '50%',
          data: priorityData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    
    priorityChart.setOption(priorityOption)
  }
  
  // 渲染趋势折线图
  if (trendChartRef.value) {
    if (trendChart) {
      trendChart.dispose()
    }
    trendChart = echarts.init(trendChartRef.value)
    
    const dates = trendData.value.map((item: any) => item.date)
    const totalData = trendData.value.map((item: any) => item.total)
    const completedData = trendData.value.map((item: any) => item.completed)
    
    const trendOption = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['总工单数', '已完成工单数']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: dates
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '总工单数',
          type: 'line',
          stack: 'Total',
          data: totalData,
          itemStyle: {
            color: '#409EFF'
          }
        },
        {
          name: '已完成工单数',
          type: 'line',
          stack: 'Total',
          data: completedData,
          itemStyle: {
            color: '#67C23A'
          }
        }
      ]
    }
    
    trendChart.setOption(trendOption)
  }
}

const getStatusLabel = (status: string) => {
  const statusMap: { [key: string]: string } = {
    pending: '待处理',
    assigned: '已分配',
    in_progress: '处理中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const getPriorityLabel = (priority: string) => {
  const priorityMap: { [key: string]: string } = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急'
  }
  return priorityMap[priority] || priority
}

// 窗口大小变化时重新调整图表大小
const handleResize = () => {
  statusChart?.resize()
  priorityChart?.resize()
  trendChart?.resize()
}

onMounted(() => {
  loadReportData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  statusChart?.dispose()
  priorityChart?.dispose()
  trendChart?.dispose()
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.work-order-reports {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.filter-card {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
}

.stats-item {
  padding: 20px 0;
}

.stats-value {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stats-label {
  font-size: 14px;
  color: #666;
}

.page-container {
  padding: 20px;
}
</style>
